package com.neuqsoft.ymtdemo.view;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.GeolocationPermissions;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.BridgeWebViewClient;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.github.lzyzsd.jsbridge.DefaultHandler;
import com.neuqsoft.ymtdemo.R;
import com.neuqsoft.ymtdemo.utils.UrlUtils;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.io.File;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;


public class WebViewEsscH5Activity extends Activity {
    private BridgeWebView mWebView;
    private Uri imageUri;
    private ValueCallback<Uri[]> mFilePathCallback;
    private static final int REQUEST_CODE = 1001;
    private static final int REQUEST_IMAGE = 1002;
    private static final int REQUEST_SCAN = 1003;
    private static final String APP_ID = "wx32efa175f67fe677";
    private CallBackFunction callBackFunction;
    private boolean isHasCode = true;
    private String strReferer;
    private HashMap<String, String> stringStringHashMap;
    private boolean isFirstLoad = false;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.web_js_view_layout);
        initView();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        Bundle bundle = intent.getExtras();
        if (bundle != null && bundle.containsKey("extraData")) {
            String extraData = bundle.getString("extraData");
            Log.e("onNewIntent__extraData", extraData);
            if (callBackFunction != null) {
                callBackFunction.onCallBack(extraData);
            }
        }

    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initView() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission_group.STORAGE, Manifest.permission.RECORD_AUDIO, Manifest.permission_group.LOCATION}, 0);
        mWebView = (BridgeWebView) findViewById(R.id.web);
        mWebView.setDefaultHandler(new DefaultHandler());

        mWebView.registerHandler("pullApp", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction callBackFunction) {
                Map<String, String> strData = JSONObject.parseObject(data, Map.class);
                String url = strData.get("url");
                if (!TextUtils.isEmpty(url)) {
                    mWebView.loadUrl(url);
                }else{
                    String path = strData.get("path");
                    String code = strData.get("code");
                    String wx_id = strData.get("wx_id");
                    String wx_type = strData.get("wx_type");//0 1 2
                    Log.e("str   :", path);
                    IWXAPI api = WXAPIFactory.createWXAPI(WebViewEsscH5Activity.this, APP_ID);
                    WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
                    req.userName = wx_id; // 填小程序原始id
                    if (TextUtils.isEmpty(code)) {
                        req.path = path;
                    } else {
                        req.path = path + "?code=" + code; //拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
                    }
//                req.miniprogramType = WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_PREVIEW;// 可选打开 开发版，体验版和正式版
                    if (!TextUtils.isEmpty(wx_type)) {
                        assert wx_type != null;
                        req.miniprogramType = Integer.valueOf(wx_type);
                    }
                    api.sendReq(req);

                }
                WebViewEsscH5Activity.this.callBackFunction = callBackFunction;
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);

            }

            @SuppressWarnings("unused")
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String AcceptType, String capture) {
                this.openFileChooser(uploadMsg);
                Toast.makeText(WebViewEsscH5Activity.this, "openFileChooser", Toast.LENGTH_SHORT).show();
            }

            @SuppressWarnings("unused")
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String AcceptType) {
                this.openFileChooser(uploadMsg);
                Toast.makeText(WebViewEsscH5Activity.this, "openFileChooser", Toast.LENGTH_SHORT).show();
            }

            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                Toast.makeText(WebViewEsscH5Activity.this, "openFileChooser", Toast.LENGTH_SHORT).show();
            }

            /**
             * API >= 21(Android 5.0.1)回调此方法
             */


            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                mFilePathCallback = filePathCallback;
                String[] acceptTypes = fileChooserParams.getAcceptTypes();
                takePhoto(acceptTypes);
                Toast.makeText(WebViewEsscH5Activity.this, "onShowFileChooser", Toast.LENGTH_SHORT).show();
                return true;
            }

            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                super.onGeolocationPermissionsShowPrompt(origin, callback);
                callback.invoke(origin, true, true);
            }
        });

        mWebView.setWebViewClient(new BridgeWebViewClient(mWebView) {


            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Map<String, String> headers = new HashMap<>();
                if (url.contains("wx.tenpay.com")) {
                    //wx.tenpay.com 收银台点击微信时，shouldOverrideUrlLoading会调用两次，这里是第二次
                    headers.put("Referer", strReferer);//第三方支付平台请求头 一般是对方固定
                } else if (url.startsWith("alipays:") || url.startsWith("alipay")) {
                    try {
                        startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                    } catch (Exception e) {
                        new AlertDialog.Builder(WebViewEsscH5Activity.this)
                                .setMessage("未检测到支付宝客户端，请安装后重试。")
                                .setPositiveButton("立即安装", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Uri alipayUrl = Uri.parse("https://d.alipay.com");
                                        startActivity(new Intent("android.intent.action.VIEW", alipayUrl));
                                    }
                                }).setNegativeButton("取消", null).show();
                    }
                    return true;
                } else if (url.startsWith("e-sscard")) {
                    if (url.startsWith("e-sscard://scanIntercept")) {
                        Intent intent = new Intent(WebViewEsscH5Activity.this, CaptureActivity.class);
                        startActivityForResult(intent, REQUEST_SCAN);
                    }
                    return true;
                } else if (url.startsWith("upwrp://")) {
                    try {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                        return true;
                    } catch (Exception e) {
                        return false;
                    }

                } else if (url.startsWith("ymt://wechate/applet")) {
                    HashMap<String, String> urlParams = UrlUtils.getUrlParams(url);
                    String path = urlParams.get("path");
                    String code = urlParams.get("code");
                    String wx_id = urlParams.get("wx_id");
                    String wx_type = urlParams.get("wx_type");//0 1 2
                    if (!TextUtils.isEmpty(path)) {
                        Log.e("str   :", path);
                    }
                    IWXAPI api = WXAPIFactory.createWXAPI(WebViewEsscH5Activity.this, APP_ID);
                    WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
                    req.userName = wx_id; // 填小程序原始id
                    if (TextUtils.isEmpty(code)) {
                        req.path = path;
                    } else {
                        req.path = path + "?code=" + code; //拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
                    }
//                req.miniprogramType = WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_PREVIEW;// 可选打开 开发版，体验版和正式版
                    if (!TextUtils.isEmpty(wx_type)) {
                        assert wx_type != null;
                        req.miniprogramType = Integer.valueOf(wx_type);
                    }
                    api.sendReq(req);

                    return true;
                } else if (url.startsWith("https")) {
                    return false;
                }
                doSchemeJump(url, headers);
                return true;
            }
        });


        WebSettings webSettings = mWebView.getSettings();
        webSettings.setAllowContentAccess(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);//设置允许js弹出alert对话框
        webSettings.setAppCacheEnabled(false);
        webSettings.setSaveFormData(false);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setGeolocationEnabled(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);  //设置 缓存模式
//        webSettings.setDefaultTextEncodingName("UTF-8");
        String url = getIntent().getStringExtra("direurl");
        strReferer = getIntent().getStringExtra("Referer");
        String userAgentString = webSettings.getUserAgentString();
        webSettings.setUserAgentString(userAgentString + ";ggfwcd");
        Log.i("tag", url);
//        mWebView.loadUrl("https://service.neuqsoft.com/ggfw/feedback/#/feedback-platform/index/GGFWQHD/130322199204061011");
        stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("Referer", strReferer);
//        url="https://wxcs.hebbank.com/ares-mobile-gateway/wxbank/cdGasPay.do";
        mWebView.loadUrl(url, stringStringHashMap);
    }

    /**
     * 根据scheme 协议作出响应跳转是跳系统浏览器还是应用内页面还是用webView 打开
     */
    public void doSchemeJump(String linkUrl, Map<String, String> headers) {
        try {
            Log.i("doSchemeJump", linkUrl);

            if (!TextUtils.isEmpty(linkUrl)) {
                Uri uri = Uri.parse(linkUrl);
                String scheme = uri.getScheme();

                if (scheme.equals("http") || scheme.equals("https")) {
                    Log.i("doSchemeJump>loadUrl>>", linkUrl);


                    loadUrl(linkUrl, uri, headers);
                } else {
                    Log.i("doSchemeJump>loadUrl>>", linkUrl);

                    openBrowser(linkUrl);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void loadUrl(String linkUrl, Uri uri, Map<String, String> headers) {
        Bundle bundle = parseExtras(uri);
        if (bundle != null) {
            if (bundle.containsKey("scheme")) {
                String scheme = bundle.getString("scheme");
                if (scheme != null && scheme.startsWith("alipays")) {
                    String schemeUrl = URLDecoder.decode(scheme);
                    try {

                        // 调用系统浏览器
                        Log.i("loadUrl>>>open>>", linkUrl);

                        open(schemeUrl);
                    } catch (Exception e) {
                        e.printStackTrace();
                        openBrowser(linkUrl);
                        finish();
                    }
                    return;
                }
            }
        }

        Log.i("loadUrl>>webview加载url>>", linkUrl);

        mWebView.loadUrl(linkUrl, headers);
    }

    public static Bundle parseExtras(Uri uri) {
        Bundle extras = null;
        Set<String> queryParameterNames = uri.getQueryParameterNames();
        for (String key : queryParameterNames) {
            String value = uri.getQueryParameter(key);
            if (extras == null) {
                extras = new Bundle();
            }
            extras.putString(key, value);
        }

        return extras;
    }

    private void openBrowser(String url) {
        try {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void open(String url) throws URISyntaxException {
        Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
        intent.addCategory("android.intent.category.BROWSABLE");
        intent.setComponent(null);
        startActivity(intent);
    }



    /**
     * 调用相机
     */
    private void takePhoto(String[] acceptTypes) {
        // 指定拍照存储位置的方式调起相机
        if (acceptTypes[0].equals("image/*")) {
            String fileName = "IMAGE_" + DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
            String filePath = Environment.getExternalStorageDirectory() + File.separator
                    + Environment.DIRECTORY_PICTURES + File.separator;
            File file = new File(filePath + fileName);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                imageUri = FileProvider.getUriForFile(this, getPackageName() + ".fileProvider", file);
            } else {
                imageUri = Uri.fromFile(file);
            }
            Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

            Intent Photo = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            Intent chooserIntent = Intent.createChooser(Photo, "Image Chooser");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{captureIntent});

            startActivityForResult(chooserIntent, REQUEST_IMAGE);
        } else if (acceptTypes[0].equals("video/*")) {
            String fileName = "VADIO_" + DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".mp4";
            String filePath = Environment.getExternalStorageDirectory() + File.separator
                    + Environment.DIRECTORY_MOVIES + File.separator;
            File file = new File(filePath + fileName);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                imageUri = FileProvider.getUriForFile(this, getPackageName() + ".fileProvider", file);
            } else {
                imageUri = Uri.fromFile(file);
            }
            Intent vadioIntent = new Intent(android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
            vadioIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            vadioIntent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 60);
            startActivityForResult(vadioIntent, REQUEST_CODE);
        }

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {//
            case 0://如果申请权限回调的参数
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    Toast.makeText(this, "申请成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "拒绝权限", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            // 经过上边(1)、(2)两个赋值操作，此处即可根据其值是否为空来决定采用哪种处理方法
            if (mFilePathCallback != null) {
                if (RESULT_OK == resultCode) {
                    updatePhotos();
                    if (data != null) {
                        // 这里是针对从文件中选图片的处理
                        Uri[] results;
                        Uri uriData = data.getData();
                        if (uriData != null) {
                            results = new Uri[]{uriData};
                            for (Uri uri : results) {
                                Log.e("WebViewEsscH5Activity", "系统返回URI：" + uri.toString());
                            }
                            mFilePathCallback.onReceiveValue(results);
                        } else {
                            mFilePathCallback.onReceiveValue(null);
                        }
                    } else {
                        Log.e("WebViewEsscH5Activity", "自定义结果：" + imageUri.toString());
                        mFilePathCallback.onReceiveValue(new Uri[]{imageUri});
                    }
                } else {
                    mFilePathCallback.onReceiveValue(null);
                }
                mFilePathCallback = null;
            }
        } else if (requestCode == REQUEST_IMAGE) {
            if (null == mFilePathCallback) {
                return;
            }
            Uri[] results = null;
            if (resultCode == Activity.RESULT_OK) {
                if (data == null) {
                    results = new Uri[]{imageUri};
                } else {
                    String dataString = data.getDataString();
                    ClipData clipData = data.getClipData();
                    if (clipData != null) {
                        results = new Uri[clipData.getItemCount()];
                        for (int i = 0; i < clipData.getItemCount(); i++) {
                            ClipData.Item item = clipData.getItemAt(i);
                            results[i] = item.getUri();
                        }
                    }
                    if (dataString != null)
                        results = new Uri[]{Uri.parse(dataString)};
                }
            }
            mFilePathCallback.onReceiveValue(results);
            mFilePathCallback = null;
        } else if (requestCode == REQUEST_SCAN) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    HashMap<String, String> map = new HashMap<>();
                    map.put("code", "01");
                    map.put("result", result);
                    String jsonString = JSONObject.toJSONString(map);
                    String json = "\'" + jsonString + "\'";
                    mWebView.loadUrl("javascript:Hybrid.handleESSCscan(" + json + ")");
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(this, "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        } else {
            Toast.makeText(this, "发生错误", Toast.LENGTH_SHORT).show();
        }
    }

    private void updatePhotos() {
        // 该广播即使多发（即选取照片成功时也发送）也没有关系，只是唤醒系统刷新媒体文件
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(imageUri);
        sendBroadcast(intent);
    }

    /**
     * 网页回退
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
            mWebView.goBack();// 返回前一个页面
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    private void syncCookie(String url) {

    }
}
